package com.example.administrator.androidros.activity;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.example.administrator.androidros.R;
import com.example.administrator.androidros.adapter.DeviceAdapter;
import com.example.administrator.androidros.base.BaseActivity;
import com.example.administrator.androidros.fragment.AuthorizedFragment;
import com.example.administrator.androidros.fragment.DeviceListFragment;
import com.example.administrator.androidros.model.ApplianceModel;
import com.example.administrator.androidros.net.HttpUtils;
import com.example.administrator.androidros.utils.AgentConstants;
import com.example.administrator.androidros.utils.AgentSharedPreferences;
import com.example.administrator.androidros.utils.ServerConstants;
import com.example.administrator.androidros.utils.StringUtils;
import com.example.administrator.androidros.utils.UUIDUtil;
import com.example.administrator.androidros.widget.ApplyDialog;
import com.example.administrator.androidros.widget.CustomTipDialog;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public class DeviceActivity extends BaseActivity {
    private static final String TAG = "hhc";
    @BindView(R.id.common_head_more)
    protected ImageView common_head_more;

    @BindView(R.id.activity_device_viewpager)
    protected ViewPager activity_device_viewpager;

    @BindView(R.id.activity_device_list_tab)
    protected TabLayout activity_device_list_tab;

    private List<Integer> moreIconList = new ArrayList<>();//更多
    private List<String> moreTitleList = new ArrayList<>();
    private List<ApplianceModel> data = new ArrayList<>();
    private String title;
    private String masterId;
    private DeviceAdapter deviceAdapter;
    private ApplianceModel applianceModel;

    private FragmentPagerAdapter fragmentPagerAdapter;
    private List<Fragment> fragmentList;
    private DeviceListFragment deviceListFragment;
    private DeviceListFragment authorizedListFragment;

    private List<String> titleList;
    private int state = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    protected void setContentView() {
        setContentView(R.layout.activity_device);
    }

    @Override
    protected void initData() {
        getIntentData();
        initCommonHeader();
        initFragmentList();
        initViewPager();
//        initMoreData();
//        initView();
    }

    @Override
    protected void onFailure(int requestCode, Object object) {

    }

    @Override
    protected void onSuccess(int requestCode, Object object) {
        stopTipDialog();
        if (object != null) {
            switch (requestCode) {
//                case 1001:
//                    if (HttpUtils.getResultCode(object).equals(AgentConstants.RESULT_CODE_OK)) {
//                        showToast(HttpUtils.getResultMessage(object));
////                        getApplianceList();
//                    } else {
//                        showToast(HttpUtils.getResultMessage(object));
//                    }
//                    break;
//                case 1002:
//                    if (HttpUtils.getResultCode(object).equals(AgentConstants.RESULT_CODE_OK)) {
//                        ApplianceModel[] deviceModels = (ApplianceModel[]) HttpUtils.getData(object, ApplianceModel[].class);
//                        if (deviceModels != null) {
//                            data = Arrays.asList(deviceModels);
//                            deviceAdapter.setNewData(data);
//                        }
//                    } else {
//                        showToast(HttpUtils.getResultMessage(object));
//                    }
//                    break;
                case 1003:
                    if (HttpUtils.getResultCode(object).equals(AgentConstants.RESULT_CODE_OK)) {
                        applianceModel = (ApplianceModel) HttpUtils.getData(object, ApplianceModel.class);
                        ApplyDialog applyDialog = new ApplyDialog(mBaseActivity);
                        applyDialog.setMemberId(applianceModel.getMemberId());
                        applyDialog.setApplianceId(applianceModel.getApplianceId());
                        applyDialog.setApplianceType(StringUtils.getApplianceType(applianceModel.getApplianceType()));
                        applyDialog.setOnApplyClickListener(new ApplyDialog.OnApplyClickListener() {
                            @Override
                            public void onApplyClick(String applianceId) {
                                //不能申请自己的 不能重复申请
                                if (AgentSharedPreferences.getMemberInfo(mBaseActivity).getMemberTelephone().equals(applianceModel.getMemberId())) {
                                    showToast("您不能申请自己的设备");
                                } else {
                                    createApplyMessage(applianceModel.getMemberId(), applianceModel.getMasterId(), applianceModel.getApplianceId());
                                }
                            }
                        });
                        applyDialog.show();
                    } else {
                        showToast(HttpUtils.getResultMessage(object));
                    }
                    break;
                case 1005:
                    if (HttpUtils.getResultCode(object).equals(AgentConstants.RESULT_CODE_OK)) {
                        showToast(HttpUtils.getResultMessage(object));
                    } else {
                        showToast(HttpUtils.getResultMessage(object));
                    }
                    break;
            }
        }
    }

    protected void getIntentData() {
        // 获取意图对象
        Intent intent = getIntent();
        //获取传递的值
        title = intent.getStringExtra("title");
    }

    protected void initCommonHeader() {
        configCommonHeader(this, title, true);
    }

//    protected void initMoreData() {
//        moreIconList.add(R.mipmap.icon_homepage_select);
//        moreIconList.add(R.mipmap.icon_my_select);
//        moreTitleList.add(getString(R.string.device_add));
//        moreTitleList.add(getString(R.string.device_delete));
//    }

//    protected void initView() {
//        activity_device_list.setLayoutManager(new GridLayoutManager(this, 3));
//        deviceAdapter = new DeviceAdapter(R.layout.activity_device_item_device, data);
//        deviceAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
//            @Override
//            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
//                Bundle bundle = new Bundle();
//                bundle.putString("masterId", data.get(position).getMasterId());
//                bundle.putString("applianceName", data.get(position).getApplianceName());
//                startOtherActivity(DeviceDetailsActivity.class, bundle);
//            }
//        });
//        activity_device_list.setAdapter(deviceAdapter);
//    }

    @OnClick(R.id.common_head_more)
    protected void moreClick() {
//        getApplianceMessage("8d4f51a7-18ff-4301-8954-0a47454505a3");
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            int hasWriteSdPermission = checkSelfPermission(android.Manifest.permission.CAMERA);
            if (hasWriteSdPermission != PackageManager.PERMISSION_GRANTED) {
                requestPermissions(new String[]{
                        Manifest.permission.CAMERA
                }, 2001);
            } else {
                startScan();
            }
        } else {
            startScan();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 2001) {
            if (permissions[0].equals(android.Manifest.permission.CAMERA)
                    && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // 用户同意
                startScan();
            } else {
                // 用户不同意
                showToast(getString(R.string.common_user_refuse_authorize));
            }
        }
    }

    protected void startScan() {
        Intent intent = new Intent(this, ScanActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivityForResult(intent, 3001);
    }

//    protected void getApplianceList() {
//        JSONObject jsonObject = new JSONObject();
//        jsonObject.put("memberId", AgentSharedPreferences.getLastLoginId(mBaseActivity));
//        jsonObject.put("type", "10");
//        HttpUtils.post(mBaseActivity, 1002, ServerConstants.QUERY_APPLIANCE_LIST, jsonObject.toString(), mBaseActivity);
//        startTipDialog(CustomTipDialog.ICON_TYPE_LOADING, getString(R.string.common_loading), true);
//    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case 3001:
                if (resultCode == RESULT_OK) {
                    Bundle bundle = data.getExtras();
                    String result = bundle.getString("result");
                    try {
                        JSONObject jsonObject = JSON.parseObject(result);
                        showToast(getString(R.string.device_identify_success));
                        if (jsonObject != null) {
                            masterId = jsonObject.getString("masterId");
                            getApplianceMessage(masterId);
                        } else {
                            showToast(getString(R.string.device_qr_code_error));
                        }
                    } catch (Exception e) {
                        showToast(getString(R.string.device_qr_code_error));
                    }
                }
                break;
            default:
                break;
        }
    }

    @Override
    public void onResume() {
        super.onResume();
//        getApplianceList();
    }

    public void getApplianceMessage(String masterId) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("masterId", masterId);
        HttpUtils.post(mBaseActivity, 1003, ServerConstants.GET_APPLIANCE_MESSAGE, jsonObject.toString(), mBaseActivity);
    }

    //设备是否正在申请 或者申请成功
    public void checkAppliance() {
        JSONObject jsonObject = new JSONObject();
//        jsonObject.put("masterId", masterId);
        HttpUtils.post(mBaseActivity, 1004, ServerConstants.GET_APPLIANCE_MESSAGE, jsonObject.toString(), mBaseActivity);
    }

    public void createApplyMessage(String memberId, String applianceMasterId, String applianceId) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("masterId", UUIDUtil.get36UUID());
        jsonObject.put("messageType", "20");
        jsonObject.put("memberId", memberId);
        jsonObject.put("messageApplicant", AgentSharedPreferences.getMemberInfo(mBaseActivity).getMemberTelephone());
        jsonObject.put("applianceMasterId", applianceMasterId);
        jsonObject.put("messageTitle", "申请权限");
        jsonObject.put("messageContent", "用户(" + AgentSharedPreferences.getMemberInfo(mBaseActivity).getMemberTelephone() + ")申请设备(" + applianceId + ")权限。");
        jsonObject.put("messageRead", "0");
        jsonObject.put("messageStatus", "0");
        HttpUtils.post(mBaseActivity, 1005, ServerConstants.ADD_MESSAGE, jsonObject.toString(), mBaseActivity);
    }

    protected void initFragmentList() {
        deviceListFragment = new DeviceListFragment();
        Bundle bundle = new Bundle();
        bundle.putString("type", "10");
        deviceListFragment.setArguments(bundle);

        authorizedListFragment = new DeviceListFragment();
        Bundle bundle1 = new Bundle();
        bundle1.putString("type", "20");
        authorizedListFragment.setArguments(bundle1);

        fragmentList = new ArrayList<>();
        fragmentList.add(deviceListFragment);
        fragmentList.add(authorizedListFragment);

        titleList = new ArrayList<>();
        titleList.add("设备列表");
        titleList.add("授权列表");
    }

    protected void initViewPager() {
        fragmentPagerAdapter = new FragmentPagerAdapter(getSupportFragmentManager()) {

            @Override
            public int getCount() {
                return fragmentList.size();
            }

            @Override
            public Fragment getItem(int arg0) {
                return fragmentList.get(arg0);
            }

            @Override
            public CharSequence getPageTitle(int position) {
                return titleList.get(position);
            }
        };

        activity_device_viewpager.setAdapter(fragmentPagerAdapter);
        activity_device_viewpager.setOffscreenPageLimit(2);
        activity_device_viewpager.setCurrentItem(state);
        activity_device_list_tab.setupWithViewPager(activity_device_viewpager);
    }
}
